@page "/Register"
@using BootstrapBlazorApp.Server.Pojo
@layout LoginLayout
@inject AjaxService AjaxService
@inject SwalService SwalService
@inject NavigationManager NavigationManager

@attribute [AllowAnonymous]
<div class="login-item login-item-gitee">
    <div class="text-center">
        <h4 class="text-dark">欢迎使用码上面试</h4>
        <h4 class="text-dark">用户注册</h4>
    </div>
    <ValidateForm Model="RegisterVo" OnValidSubmit="OnValidSubmit">
        <FloatingLabel DisplayText="用户名" @bind-Value="RegisterVo.UserName" IsGroupBox="true" PlaceHolder="请输入用户名" />
        <FloatingLabel DisplayText="密码" @bind-Value="RegisterVo.Password" type="password" IsGroupBox="true" PlaceHolder="请输入密码" />
        <FloatingLabel DisplayText="确认密码" @bind-Value="RegisterVo.ConfirmPassword" type="password" IsGroupBox="true" PlaceHolder="确认密码" />
        <div style="display: flex;margin-bottom: 5%">
            <Button Text="注册" Color="Color.Primary" ButtonType="ButtonType.Submit" IsOutline="true" style="margin-right: 3%;margin-bottom: 1rem"></Button>
            <Button Text="返回登陆" Color="Color.Info" OnClick="ToLogin" IsOutline="true" style="margin-left: 3%;margin-bottom: 1rem"></Button>
        </div>
        
    </ValidateForm>
</div>

@code
{
    private RegisterVo RegisterVo { get; set; } = new RegisterVo();
    
    private void ToLogin()
    {
        NavigationManager.NavigateTo("/Login");
    }

    private async Task OnValidSubmit(EditContext arg)
    {
        try
        {
            // 使用Ajax调用注册API
            var document = await AjaxService.InvokeAsync(new AjaxOption()
            {
                Url = "/api/Account/Register",
                Data = RegisterVo // 直接传递RegisterVo对象作为数据
            });

            if (document?.RootElement.GetProperty("code").GetInt32() == 200)
            {
                await SwalService.Show(new SwalOption()
                {
                    Category = SwalCategory.Success,
                    Content = "注册成功！",
                    Title = "欢迎"
                });
                //此时无需保存交换cookie，故直接使用navigation跳转即可
                NavigationManager.NavigateTo("/Login");
            }
            else
            {
                await SwalService.Show(new SwalOption()
                {
                    Category = SwalCategory.Error,
                    Content = document?.RootElement.GetProperty("message").GetString() ?? "系统异常",
                    Title = "注册失败"
                });
            }
        }
        catch (Exception ex)
        {
            // 处理网络请求或其他异常
            await SwalService.Show(new SwalOption()
            {
                Category = SwalCategory.Error,
                Content = "发生错误：" + ex.Message,
                Title = "系统错误"
            });
        }
    }
}